using System;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb.Classes;
using YoshiBase.Classes;
using jQueryApi;

namespace YesPlayLove.Clusters
{
    [IgnoreNamespace]
    public class EmailReply : EmailBase
    {
        private jQueryObject _header;
        private jQueryObject _replyBody;
        private jQueryEventHandler _sendAction;
        private jQueryEventHandler _cancelAction;
        private string _title = EmailTheme.ReplyTitle;

        // ReSharper disable UnusedMember.Local
        private static bool _hasEvents = AttachEvents(); // Do this to get static AttachEvents to run once
        // ReSharper restore UnusedMember.Local

        public EmailReply(EmailCluster cluster)
            : base(cluster)
        {
        }

        private static bool AttachEvents()
        {
            jQuery.Select(".EmailBubble .Reply textarea").Live(
                "keypress.emailreply",
                delegate(jQueryEvent e)
                {
                    if (e.Which == 13 && e.ShiftKey)
                        jQuery.Select(".EmailBubble .Reply .SendBtn").Click();
                })
            ;
            return true;
        }

        public override EmailBase Build(bool active)
        {
            Initialize(active);

            Element
                .Hide()
                .Empty()
                .AddClass("Section RightSide Reply")
                .RemoveClass("RightSideInput")
                .Unbind("keyup.EmailReply")
                .Bind("keyup.EmailReply", delegate(jQueryEvent e) { CancelEvent(e); })
                ;

            if (active)
            {
                Element.AddClass("RightSideInput");
                _header = jQuery.FromHtml("<div class='Header'/>")
                    .AppendTo(Element)
                    .Html(_title)
                    ;

                _replyBody = jQuery.FromHtml("<textarea class='Body ReplyBody'/>")
                    .AppendTo(Element)
                    ;

                jQuery.FromHtml("<span class='ActionBtn CancelBtn'/>")
                    .AppendTo(_header)
                    .Html(EmailTheme.CancelButton)
                    .Click(_cancelAction)
                    ;

                jQuery.FromHtml("<span class='ActionBtn SendBtn'/>")
                    .AppendTo(_header)
                    .Html(EmailTheme.SendButton)
                    .Click(
                        delegate(jQueryEvent e)
                        {
                            if (String.IsNullOrEmpty(_replyBody.Plugin<Jewl>().GetFValueString()))
                            {
                                new Ask().OkAw(Await.AsyncAw, String.Format(EmailTheme.PleaseFillMsg, _title.ToLowerCase()));
                            }
                            else
                            {
                                if (EmailBubbles != null)
                                    EmailBubbles.RebuildMessage(false).AppendReply(true).FocusInput();
                                Rebuild(false);
                                Await awx = new Await();
                                awx
                                    .AddAw(Data.SendMailAw, EmailProfile.OtherPersonId, _replyBody.Plugin<Jewl>().GetFValueString());
                                if (EmailInbox != null)
                                    awx.AddAw(EmailInbox.RefreshAw);
                                awx
                                    .AddDx(delegate { if (_sendAction != null) _sendAction(e); })
                                    .Commit();
                            }
                        }
                    )
                    ;
            }
            else
            {
                _replyBody = jQuery.FromHtml("<p class='Body ReplyBody'/>")
                    .AppendTo(Element)
                    ;
            }

            return this;
        }

        public EmailReply Rebuild(bool active)
        {
            string msg = Active ? _replyBody.GetValue() : _replyBody.GetHtml();
            new Await()
                .AddAw(FadeOutAw, ThemeBase.FadeOut)
                .AddDx(delegate { Build(active).Fill(msg); })
                .AddAw(FadeInAw, ThemeBase.FadeIn)
                .Commit();
            return this;
        }

        public override EmailBase Fill(object msg)
        {
            _replyBody.Html((string)msg).Value((string)msg);
            return this;
        }

        public override EmailBase FocusInput()
        {
            new Await()
                .AddAw(SlideDownAw, ThemeBase.SlideDown)
                .AddFn(Focus, _replyBody)
                .AddAw(ScrollInViewAw, Element)
                .Commit();
            return this;
        }

        public static void SendPopupAw(Await awp, YoshiUser usr, jQueryEvent e)
        {

            jQueryObject trigger = jQuery.FromElement(e.Target);
            EmailProfile.SetOther(usr.id);
            EmailReply emm = (EmailReply)new EmailReply(null).FromHtml("<div/>");
            emm.Wrapper = jQuery.FromHtml("<div class='EmailBubble PopUp' style='position:absolute'/>")
                .AppendTo("#PageContent")
                .CSS("top", trigger.GetOffset().Top + trigger.GetHeight() - jQuery.Select("#PageContent").GetOffset().Top + "px");
            emm._cancelAction =
                delegate
                {
                    emm.Wrapper.Remove();
                    emm.HiderAw(Await.AsyncAw, false, 0);
                    emm.EscapeKeyAction();
                };
            emm._sendAction = emm._cancelAction;
            emm._title = EmailTheme.MessageTitle;
            emm.Build(true).AppendTo(emm.Wrapper).FadeInAw(Await.AsyncAw);
            emm.FocusInput();
            emm.HiderAw(Await.AsyncAw, true, .65);
            emm.EscapeKeyAction(emm._cancelAction);
            awp.Done();
        }
    }
}